package cn.geminis.warehouse.service.basic.entity;

import cn.geminis.lowcode.annotation.*;
import cn.geminis.warehouse.service.basic.entity.filter.RouteFilter;
import cn.geminis.warehouse.service.basic.entity.repository.RouteRepository;
import cn.geminis.warehouse.service.util.SpringApplicationContext;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import jakarta.persistence.Column;
import lombok.Getter;
import lombok.Setter;

import java.math.BigDecimal;

@Getter
@Setter
@UuidEntity(idFieldAnnotations = {"com.alibaba.excel.annotation.ExcelIgnore"})
@SoftDeleteEntity(deleteFieldAnnotations = {"com.alibaba.excel.annotation.ExcelIgnore"})
@QueryFilter
@CrudRepository
@CrudController
@ExcelController
public class Route {
    @Column(nullable = false)
    @ExcelProperty("起始位置")
    @QueryFilterProperty
    @QueryFilterProperty(filterType = QueryFilterProperty.FilterType.Like, valueFormat = "%%%s%%")
    private String pointStart;

    @Column(nullable = false)
    @ExcelProperty("终点位置")
    @QueryFilterProperty
    @QueryFilterProperty(filterType = QueryFilterProperty.FilterType.Like, valueFormat = "%%%s%%")
    private String pointEnd;

    @Column
    @ExcelProperty("标段")
    @QueryFilterProperty(filterType = QueryFilterProperty.FilterType.Like, valueFormat = "%%%s%%")
    private String pointEndId;

    @Column(nullable = false)
    @ExcelProperty("类型")
    @QueryFilterProperty
    @QueryFilterProperty(filterType = QueryFilterProperty.FilterType.Like, valueFormat = "%%%s%%")
    private String type;

    @Column(nullable = false)
    @ExcelProperty("距离")
    private int distance;

    @Column(nullable = false)
    @ExcelProperty("折价率")
    private BigDecimal discount;

    public static class RouteConverter implements Converter<Route> {
        @Override
        public Route convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
            var infos = cellData.getStringValue().split("-");
            var repository = SpringApplicationContext.getBean(RouteRepository.class);
            return repository.findOne(
                    RouteFilter.builder()
                            .pointStart(infos[0])
                            .pointEnd(infos[1])
                            .type(infos[2])
                            .build()
            ).get();
        }

        @Override
        public WriteCellData<?> convertToExcelData(Route value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
            return new WriteCellData<>(value.pointStart + "-" + value.pointEnd + "-" + value.type);
        }
    }
}
